package propertymgmt.gui;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

import propertymgmt.entities.Lease;
import propertymgmt.entities.Property;
import propertymgmt.entities.Tenant;
import propertymgmt.util.PropertiesManager;

/**
 * CreateNewLeaseTerm.java
 * 
 * Allows the user to create a new Lease to be associated with
 * an existing Property
 *
 * @author Brian
 */
@SuppressWarnings("serial")
public class CreateNewLeaseTerm extends javax.swing.JInternalFrame {
	
    /** Creates new form CreateNewLeaseTerm */
    public CreateNewLeaseTerm() {
        initComponents();
        loadProperties();
        toggleAllFieldsEnabled(false);
    }
    
    private void toggleAllFieldsEnabled(boolean enabled){
    	dc_startDate.setEnabled(enabled);
    	dc_endDate.setEnabled(enabled);
    	ftxt_depositAmt.setEnabled(enabled);
    	ftxt_rentAmt.setEnabled(enabled);
    	spn_rentDueDate.setEnabled(enabled);
    	spn_rentLateDate.setEnabled(enabled);
    	ftxt_lateRentFee.setEnabled(enabled);
    	ftxt_lateRentPerDay.setEnabled(enabled);
    	chk_petsAllowed.setEnabled(enabled);
    	txt_tenantFirstName.setEnabled(enabled);
    	txt_tenantLastName.setEnabled(enabled);
    	ftxt_tenantAge.setEnabled(enabled);
    	btn_addTenant.setEnabled(enabled);
    	btn_save.setEnabled(enabled);
    }
    
    private Date getStartDate(){
    	return dc_startDate.getDate();
    }
    
    private Date getEndDate(){
    	return dc_endDate.getDate();
    }
    
    private double getDepositAmt(){
    	return Double.parseDouble(ftxt_depositAmt.getText().trim());
    }
    
    private double getRentAmt(){
    	return Double.parseDouble(ftxt_rentAmt.getText().trim());
    }
    
    private int getRentDueDate(){
    	return Integer.parseInt(spn_rentDueDate.getValue().toString().trim());
    }
    
    private int getRentLateDate(){
    	return Integer.parseInt(spn_rentLateDate.getValue().toString().trim());
    }
    
    private double getLateRentFee(){
    	return Double.parseDouble(ftxt_lateRentFee.getText().trim());
    }
    
    private double getLateRentFeePerDay(){
    	return Double.parseDouble(ftxt_lateRentPerDay.getText().trim());
    }
    
    private boolean isPetsAllowed(){
    	return chk_petsAllowed.isSelected();
    }
    
    private double getPetDepositFee(){
    	if(ftxt_petDepositAmt.getText().trim().isEmpty()) return 0;
    	return Double.parseDouble(ftxt_petDepositAmt.getText().trim());
    }
    
    private boolean isPetDepositRefundable(){
    	return chk_petDepositRefundable.isSelected();
    }
    
    private ArrayList<Tenant> getTenants(){
    	ArrayList<Tenant> tenants = new ArrayList<Tenant>();
    	
    	for(int i = 0; i < list_tenants.getModel().getSize(); i++){
    		tenants.add(list_tenants.getModel().getElementAt(i));
    	}
    	
    	return tenants;
    }
    
    private String getTenantFirstName(){
    	return txt_tenantFirstName.getText().trim();
    }
    
    private String getTenantLastName(){
    	return txt_tenantLastName.getText().trim();
    }
    
    private int getTenantAge(){
    	String text = ftxt_tenantAge.getText();
    	
    	if(text != null && !text.trim().isEmpty()){
    		return Integer.parseInt(text.trim());
    	}
    	
    	return 0;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        list_properties = new javax.swing.JList<Property>();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        dc_startDate = new com.toedter.calendar.JDateChooser();
        jLabel2 = new javax.swing.JLabel();
        dc_endDate = new com.toedter.calendar.JDateChooser();
        jLabel3 = new javax.swing.JLabel();
        ftxt_depositAmt = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        ftxt_rentAmt = new javax.swing.JFormattedTextField();
        jLabel5 = new javax.swing.JLabel();
        spn_rentDueDate = new javax.swing.JSpinner();
        jLabel6 = new javax.swing.JLabel();
        spn_rentLateDate = new javax.swing.JSpinner();
        jLabel7 = new javax.swing.JLabel();
        ftxt_lateRentFee = new javax.swing.JFormattedTextField();
        jLabel8 = new javax.swing.JLabel();
        ftxt_lateRentPerDay = new javax.swing.JFormattedTextField();
        chk_petsAllowed = new javax.swing.JCheckBox();
        jLabel9 = new javax.swing.JLabel();
        ftxt_petDepositAmt = new javax.swing.JFormattedTextField();
        chk_petDepositRefundable = new javax.swing.JCheckBox();
        jPanel4 = new javax.swing.JPanel();
        btn_addTenant = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        list_tenants = new javax.swing.JList<Tenant>();
        jLabel11 = new javax.swing.JLabel();
        txt_tenantFirstName = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        txt_tenantLastName = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        ftxt_tenantAge = new javax.swing.JFormattedTextField();
        jPanel5 = new javax.swing.JPanel();
        btn_save = new javax.swing.JButton();
        btn_close = new javax.swing.JButton();
        
        setClosable(true);
        setIconifiable(true);
        setTitle("Create New Lease Term");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Properties", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N

        
        list_properties.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        list_properties.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                list_propertiesValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(list_properties);
        list_properties.setModel(new DefaultListModel<Property>());

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 220, 450));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "New Lease Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Lease Start Date");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Lease End Date");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Deposit Amount");

        ftxt_depositAmt.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("###0.##"))));

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("Rent Amount");

        ftxt_rentAmt.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("###0.##"))));

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setText("Day of Month Rent Is Due");

        spn_rentDueDate.setModel(new javax.swing.SpinnerNumberModel(1, 1, 31, 1));

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setText("Day of Month Rent Is Late");

        spn_rentLateDate.setModel(new javax.swing.SpinnerNumberModel(1, 1, 31, 1));

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Late Rent Fee");
        jLabel7.setToolTipText("A flat fee just for being late");

        ftxt_lateRentFee.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("###0.##"))));
        ftxt_lateRentFee.setToolTipText("A flat fee just for being late");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Late Rent Fee Per Day");
        jLabel8.setToolTipText("A fee for every day that the rent is late");

        ftxt_lateRentPerDay.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("###0.##"))));
        ftxt_lateRentPerDay.setToolTipText("A fee for every day that the rent is late");

        chk_petsAllowed.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        chk_petsAllowed.setText("Pets Allowed");
        chk_petsAllowed.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chk_petsAllowedActionPerformed(evt);
            }
        });

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel9.setText("Pet Deposit Fee");
        jLabel9.setEnabled(false);

        ftxt_petDepositAmt.setEnabled(false);

        chk_petDepositRefundable.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        chk_petDepositRefundable.setText("Pet Deposit Refundable");
        chk_petDepositRefundable.setEnabled(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8)
                    .addComponent(chk_petsAllowed))
                .addGap(70, 70, 70)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(chk_petDepositRefundable)
                    .addComponent(spn_rentLateDate, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ftxt_depositAmt, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(spn_rentDueDate, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(ftxt_lateRentPerDay, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(ftxt_lateRentFee, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(ftxt_rentAmt, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
                        .addComponent(ftxt_petDepositAmt, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(dc_endDate, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                    .addComponent(dc_startDate, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dc_startDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(22, 22, 22)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(dc_endDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jLabel3))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(ftxt_depositAmt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jLabel4))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(ftxt_rentAmt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jLabel5))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(spn_rentDueDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jLabel6))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(spn_rentLateDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(ftxt_lateRentFee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(ftxt_lateRentPerDay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(chk_petsAllowed)
                        .addComponent(jLabel9))
                    .addComponent(ftxt_petDepositAmt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(chk_petDepositRefundable)
                .addContainerGap(40, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 10, 480, 450));

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Tenants", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btn_addTenant.setText("Add Tenant");
        btn_addTenant.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	btn_addTenantActionPerformed(evt);
            }
        });
        jPanel4.add(btn_addTenant, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 150, -1, -1));

        list_tenants.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane3.setViewportView(list_tenants);
        list_tenants.setModel(new DefaultListModel<Tenant>());

        jPanel4.add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 180, 150));

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel11.setText("First Name");
        jPanel4.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 30, -1, 20));
        jPanel4.add(txt_tenantFirstName, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 30, 350, -1));

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel12.setText("Last Name");
        jPanel4.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 60, -1, 20));
        jPanel4.add(txt_tenantLastName, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 60, 350, -1));

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel13.setText("Age");
        jPanel4.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 90, -1, -1));

        ftxt_tenantAge.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("###"))));
        jPanel4.add(ftxt_tenantAge, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 90, 140, -1));

        getContentPane().add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 470, 720, 190));

        jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btn_save.setText("Save");        
        btn_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	btn_saveActionPerformed(evt);
            }
        });
        jPanel5.add(btn_save, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 10, 80, -1));

        btn_close.setText("Close");
        btn_close.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_closeActionPerformed(evt);
            }
        });
        jPanel5.add(btn_close, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 10, 80, -1));

        getContentPane().add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 660, 740, 40));

        pack();
    }// </editor-fold>
    
    private Property getCurrentChosenProperty(){
    	Object selectedValue = list_properties.getSelectedValue();
    	
    	if(selectedValue != null){
    		return (Property) selectedValue;
    	}
    	
    	return null;
    }
    
    private void list_propertiesValueChanged(javax.swing.event.ListSelectionEvent evt) {
        if(evt.getValueIsAdjusting() == false){
        	if(getCurrentChosenProperty() != null){
        		toggleAllFieldsEnabled(true);
        	}
        }
    }

    private void chk_petsAllowedActionPerformed(java.awt.event.ActionEvent evt) {
        jLabel9.setEnabled(chk_petsAllowed.isSelected());
        ftxt_petDepositAmt.setEnabled(chk_petsAllowed.isSelected());
        chk_petDepositRefundable.setEnabled(chk_petsAllowed.isSelected());
    }

    private void btn_closeActionPerformed(java.awt.event.ActionEvent evt) {
        dispose();
    }
    
    private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {
        if(checkLeaseFields()){
        	Property currentProperty = getCurrentChosenProperty();
        	if(currentProperty == null) return;
        	
        	if(!currentProperty.alreadyHasLeaseDuringDates(getStartDate(), getEndDate())){
	        	Lease newLease = new Lease(currentProperty, getStartDate(), getEndDate(), getDepositAmt(), getRentAmt(),
	        			getRentDueDate(), getRentLateDate(), getLateRentFee(), getLateRentFeePerDay(), getTenants(), isPetsAllowed(),
	        			getPetDepositFee(), isPetDepositRefundable());
	        	
	        	for(Tenant tenant : getTenants()){
	        		tenant.setLease(newLease);
	        	}
	    		
	    		boolean added = currentProperty.addLease(newLease);
	    		
	    		if(!added){
	    			System.err.println("Lease already exists, not adding");
	    		}
	    		
	    		PropertiesManager.getInstance().saveDbState();
	    		clearLeaseFields();
	    		clearTenantFields();
        	}else {
        		JOptionPane.showMessageDialog(this, "There is already a lease for this property during these dates",
        				"Lease dates already exist", JOptionPane.ERROR_MESSAGE);
        	}
        }
    }
    
    private void clearLeaseFields(){
    	dc_startDate.setDate(null);
    	dc_endDate.setDate(null);
    	ftxt_depositAmt.setText(null);
    	ftxt_rentAmt.setText(null);
    	spn_rentDueDate.setValue(1);
    	spn_rentLateDate.setValue(1);
    	ftxt_lateRentFee.setText(null);
    	ftxt_lateRentPerDay.setText(null);
    	chk_petsAllowed.setSelected(false);
    }
    
    private void clearTenantFields(){
    	((DefaultListModel<Tenant>)list_tenants.getModel()).clear();
    	txt_tenantFirstName.setText(null);
    	txt_tenantLastName.setText(null);
    	ftxt_tenantAge.setText(null);
    }
    
    private void btn_addTenantActionPerformed(java.awt.event.ActionEvent evt) {
    	if(checkTenantFields()){
    		Tenant newTenant = new Tenant(getTenantFirstName(), getTenantLastName(), getTenantAge());
    		
        	((DefaultListModel<Tenant>)list_tenants.getModel()).addElement(newTenant);
        	
        	txt_tenantFirstName.setText(null);
        	txt_tenantLastName.setText(null);
        	ftxt_tenantAge.setText(null);
        	
        	txt_tenantFirstName.requestFocus();
    	}
    }
    
    private void loadProperties(){
    	List<Property> allProperties = PropertiesManager.getInstance().getAllProperties();
    	
    	if(allProperties != null && allProperties.size() != 0){
    		for(Property property : allProperties){
    			((DefaultListModel<Property>) list_properties.getModel()).addElement(property);
    		}
    	}
    }
    
    private boolean checkLeaseFields(){
    	boolean passed = dc_startDate.getDate() != null;
    	passed &= dc_endDate.getDate() != null;
    	passed &= !ftxt_depositAmt.getText().trim().isEmpty();
    	passed &= !ftxt_rentAmt.getText().trim().isEmpty();
    	passed &= list_tenants.getModel().getSize() != 0;
    	if(chk_petsAllowed.isSelected()){
    		passed &= !ftxt_petDepositAmt.getText().trim().isEmpty();
    	}
    	
    	if(!passed){
    		JOptionPane.showMessageDialog(this, "Please fill in all of the following fields:\n" +
    				"Lease start date \nLease end date \ndeposit amount \nrent amount \npet " +
    				"depost fee (if appropriate)\nand there must be at least one tenant");
    	}
    	
    	return passed;
    }

    private boolean checkTenantFields(){
    	boolean passed = !txt_tenantFirstName.getText().trim().isEmpty();
    	passed &= !txt_tenantLastName.getText().trim().isEmpty();
    	
    	if(!passed){
    		JOptionPane.showMessageDialog(this, "Tenant first and last name must be provided");
    	}
    	
    	return passed;
    }

    // Variables declaration - do not modify
    private javax.swing.JButton btn_addTenant;
    private javax.swing.JButton btn_close;
    private javax.swing.JButton btn_save;
    private javax.swing.JCheckBox chk_petDepositRefundable;
    private javax.swing.JCheckBox chk_petsAllowed;
    private com.toedter.calendar.JDateChooser dc_endDate;
    private com.toedter.calendar.JDateChooser dc_startDate;
    private javax.swing.JFormattedTextField ftxt_depositAmt;
    private javax.swing.JFormattedTextField ftxt_lateRentFee;
    private javax.swing.JFormattedTextField ftxt_lateRentPerDay;
    private javax.swing.JFormattedTextField ftxt_petDepositAmt;
    private javax.swing.JFormattedTextField ftxt_rentAmt;
    private javax.swing.JFormattedTextField ftxt_tenantAge;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JList<Property> list_properties;
    private javax.swing.JList<Tenant> list_tenants;
    private javax.swing.JSpinner spn_rentDueDate;
    private javax.swing.JSpinner spn_rentLateDate;
    private javax.swing.JTextField txt_tenantFirstName;
    private javax.swing.JTextField txt_tenantLastName;
    // End of variables declaration

}
